package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-06-05
 * Time: 21:44
 */
//reentrantLock可重入锁，同一线程可以多次获取同一把锁，不会造成死锁。
public class Demo41 {

    private static int count = 0;

    public static void main(String[] args) {
        ReentrantLock locker = new ReentrantLock();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 500000; i++) {
                    locker.lock();
                    try {
                        count++;
                    }finally {
                        locker.unlock();//确保释放锁
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 500000; i++) {
                    locker.lock();
                    try {
                        count++;
                    }finally {
                        locker.unlock();
                    }
                }
            }
        });
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("count = " + count);
    }
}
